package com.zztl.infiniteBand.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsMessage
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleNoticiCallback
import com.zztl.infiniteBand.storage.BillPreference
import com.zztl.infiniteBand.storage.PreferenceKeys
import java.io.UnsupportedEncodingException


/**
 * Created by caspar on 2017/4/11.
 */

class SMSBroadcastReceiver : BroadcastReceiver(), BleNoticiCallback {

    private var contentList: MutableList<ByteArray>? = null
    private var id = 1
    private var mMsgPhoneNum: String? = null
    private var mMsgBody: String? = null


    override fun onReceive(arg0: Context, intent: Intent) {
        if (intent.action == "android.provider.Telephony.SMS_RECEIVED") {
            if (intent.action === "android.provider.Telephony.SMS_RECEIVED") {
                val bundle = intent.extras
                var msg: SmsMessage? = null
                if (null != bundle) {
                    val smsObj = bundle.get("pdus") as Array<Any>
                    if (smsObj.isNotEmpty()) {
                        for (`object` in smsObj) {
                            msg = SmsMessage.createFromPdu(`object` as ByteArray)
                            mMsgPhoneNum = msg!!.originatingAddress
                            mMsgBody = msg.displayMessageBody
                            try {
                                contentList = ContentUtil.getContentByteList(mMsgBody!!) as MutableList<ByteArray>
                            } catch (e: UnsupportedEncodingException) {
                                e.printStackTrace()
                            }

                        }
                    }

                    if ( BillPreference.getApp(PreferenceKeys.SMSTOGGLE.name, false) as Boolean) {
                        if(id==255) id=1 else id++
                        contentList?.run {
                            BleManager.getInstance().dataComonent.pushNotice(id,1,3,this[0],this@SMSBroadcastReceiver)
                        }

                    }

                }
            }

        }
    }


    override fun noticiSuccess(isSuccess: Boolean) {
        if (isSuccess) {
            contentList?.apply {
                if (isSuccess && size > 0) {
                    removeAt(0)
                    if (size > 0) {
                        if(id==255) id=1 else id++
                        Thread.sleep(1000)
                        BleManager.getInstance().dataComonent.pushNotice(id, 1, 3, this[0], this@SMSBroadcastReceiver)
                    }
                }
            }
        }
    }



}
